package com.itheima.wisdomnext.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.easysdk.factory.Factory;
import com.itheima.wisdomnext.config.AliPayConfig;
import com.itheima.wisdomnext.entity.AliPay;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/alipay")
@Transactional(rollbackFor = Exception.class)
public class AliPayController {

    @Resource
    private AliPayConfig aliPayConfig;

    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "utf-8";
    private static final String SIGN_TYPE = "RSA2";

    @GetMapping("/report/pay")
    public void reportPay(@RequestParam("amount") String amount, HttpServletResponse httpResponse) throws Exception {
        // 创建唯一订单号（可用 UUID 简化）
        String traceNo = UUID.randomUUID().toString().replace("-", "").substring(0, 20);

        // 构建支付请求
        AlipayClient alipayClient = new DefaultAlipayClient(
                GATEWAY_URL,
                aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),
                FORMAT,
                CHARSET,
                aliPayConfig.getAlipayPublicKey(),
                SIGN_TYPE
        );

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());

        // 设置支付内容，使用传入的 amount 参数
        String bizContent = String.format(
                "{" +
                        "\"out_trade_no\":\"%s\"," +
                        "\"total_amount\":\"%s\"," +
                        "\"subject\":\"举报处理费用\"," +
                        "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"" +
                        "}", traceNo, amount);

        request.setBizContent(bizContent);

        try {
            String form = alipayClient.pageExecute(request).getBody();
            httpResponse.setContentType("text/html;charset=" + CHARSET);
            httpResponse.getWriter().write(form);
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            httpResponse.getWriter().write("支付请求失败：" + e.getMessage());
        }
    }

    @PostMapping("/notify")
    public String payNotify(HttpServletRequest request) throws Exception {
        if ("TRADE_SUCCESS".equals(request.getParameter("trade_status"))) {
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            boolean verified = Factory.Payment.Common().verifyNotify(params);
            if (verified) {
                // ✅ 验签通过 - 打印举报支付信息
                System.out.println("✅ 举报支付成功！");
                System.out.println("交易号: " + params.get("trade_no"));
                System.out.println("支付时间: " + params.get("gmt_payment"));
                System.out.println("买家ID: " + params.get("buyer_id"));
            } else {
                System.out.println("❌ 举报支付验签失败！");
            }
        }
        return "success";
    }
}
